from datetime import datetime
from typing import Optional, Dict, List
from loguru import logger
from app.utils.logger import log_exception

class AlarmService:
    def __init__(self):
        self.alarm_status: Dict[str, Dict] = {}  # 存储报警状态
        self.alarm_history: List[Dict] = []  # 存储报警历史记录
        
    @log_exception
    async def trigger_timeout_alarm(self, door_id: str):
        """触发超时报警"""
        try:
            # 创建报警数据
            alarm_data = {
                "door_id": door_id,
                "alarm_type": "timeout",
                "alarm_time": datetime.now(),
                "description": "门禁超过15分钟未关闭",
                "status": "active"
            }
            
            # 记录报警
            await self._record_alarm(alarm_data)
            
            # 发送报警通知
            await self._notify_alarm(alarm_data)
            
            # 触发海康平台报警
            await self._trigger_hikvision_alarm(door_id, alarm_data)
            
            logger.warning(f"已触发超时报警: {door_id}")
            
        except Exception as e:
            logger.error(f"触发超时报警失败: {str(e)}")
            raise
            
    @log_exception
    async def trigger_force_open_alarm(self, door_id: str):
        """触发强制开门报警"""
        try:
            alarm_data = {
                "door_id": door_id,
                "alarm_type": "force_open",
                "alarm_time": datetime.now(),
                "description": "检测到强制开门",
                "status": "active"
            }
            
            await self._record_alarm(alarm_data)
            await self._notify_alarm(alarm_data)
            await self._trigger_hikvision_alarm(door_id, alarm_data)
            
            logger.warning(f"已触发强制开门报警: {door_id}")
            
        except Exception as e:
            logger.error(f"触发强制开门报警失败: {str(e)}")
            raise
            
    @log_exception
    async def clear_alarm(self, door_id: str):
        """清除报警"""
        try:
            if door_id in self.alarm_status:
                alarm_data = self.alarm_status[door_id]
                alarm_data["status"] = "cleared"
                alarm_data["clear_time"] = datetime.now()
                
                # 更新报警记录
                await self._record_alarm(alarm_data)
                
                # 从活动报警中移除
                del self.alarm_status[door_id]
                
                # 通知报警解除
                await self._notify_alarm_clear(alarm_data)
                
                logger.info(f"已清除报警: {door_id}")
                
        except Exception as e:
            logger.error(f"清除报警失败: {str(e)}")
            raise
            
    async def _record_alarm(self, alarm_data: dict):
        """记录报警信息"""
        try:
            # 更新当前报警状态
            if alarm_data["status"] == "active":
                self.alarm_status[alarm_data["door_id"]] = alarm_data
            
            # 添加到历史记录
            self.alarm_history.append(alarm_data.copy())
            
            # TODO: 将报警记录保存到数据库
            logger.info(f"报警记录已保存: {alarm_data}")
            
        except Exception as e:
            logger.error(f"记录报警信息失败: {str(e)}")
            raise
            
    async def _notify_alarm(self, alarm_data: dict):
        """发送报警通知"""
        try:
            # TODO: 实现报警通知方式，如：
            # 1. 发送邮件
            # 2. 发送短信
            # 3. 推送到监控平台
            # 4. 触发声光报警器
            
            logger.info(f"报警通知已发送: {alarm_data}")
            
        except Exception as e:
            logger.error(f"发送报警通知失败: {str(e)}")
            raise
            
    async def _notify_alarm_clear(self, alarm_data: dict):
        """发送报警解除通知"""
        try:
            # TODO: 实现报警解除通知
            logger.info(f"报警解除通知已发送: {alarm_data}")
            
        except Exception as e:
            logger.error(f"发送报警解除通知失败: {str(e)}")
            raise
            
    async def _trigger_hikvision_alarm(self, door_id: str, alarm_data: dict):
        """触发海康平台报警"""
        try:
            # TODO: 调用海康平台的报警接口
            logger.info(f"已触发海康平台报警: {door_id}")
            
        except Exception as e:
            logger.error(f"触发海康平台报警失败: {str(e)}")
            raise
            
    def get_active_alarms(self) -> List[Dict]:
        """获取当前活动的报警"""
        return list(self.alarm_status.values())
        
    def get_alarm_history(self, door_id: Optional[str] = None) -> List[Dict]:
        """获取报警历史记录"""
        if door_id:
            return [alarm for alarm in self.alarm_history if alarm["door_id"] == door_id]
        return self.alarm_history
